#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "../inc/defs.h"
#include "../inc/fmanager.h"
#include "../inc/log.h"

struct fmanagerCDT
{
	FILE *	dbase;
	int		dbsize;
};

fmanagerADT 
NewfManager(const char * name, int size)
{
	fmanagerADT fmanager;
	
	if ( Precondicion(name) || size <= 0 )
		return NULL;
		
	if ( (fmanager = malloc(sizeof(struct fmanagerCDT))) == NULL )
	{
		Error("NewfManager@fmanagerADT.c - Not enough memory to create file manager\n");
		return NULL;
	}
	
	if ( (fmanager -> dbase = fopen(name, "w+b")) == NULL )
	{
		Error("NewfManager@fmanagerADT.c - Could not create file %s\n", name);
		free(fmanager);
		return NULL;
	}
	
	fmanager -> dbsize = size;
	
	return fmanager;
}


fmanagerADT 
OpenfManager(const char * name, const char * mode, int size)
{
	fmanagerADT fmanager;
	
	if ( Precondicion(name) || size <= 0 )
		return NULL;
		
	if ( (fmanager = malloc(sizeof(struct fmanagerCDT))) == NULL )
	{
		Error("OpenfManager@fmanagerADT.c - Not enough memory to create file manager\n");
		return NULL;
	}
	
	if ( (fmanager -> dbase = fopen(name, mode)) == NULL )
	{
		free(fmanager);
		return NULL;
	}
	
	fmanager -> dbsize = size;
	
	
	return fmanager;
}

int 
fmread(fmanagerADT fmanager, int nmemb, void * buffer)
{
	int ok;
	
	if ( Precondicion(fmanager) || Precondicion(buffer) || nmemb <= 0 )
	{
		Error("fmread@fmanagerADT.c - Invalid arguments\n");
		return -1;
	}
	
	ok = fread(buffer, fmanager -> dbsize, nmemb, fmanager -> dbase);
	
	return ok;
}

int 
fmwrite(fmanagerADT fmanager, int nmemb, void * buffer)
{
	int ok;
	if ( Precondicion(fmanager) || Precondicion(buffer) || nmemb <= 0 )
	{
		Error("fmwrite@fmanagerADT.c - Invalid arguments\n");
		return -1;
	}
	
	ok = fwrite(buffer, fmanager -> dbsize, nmemb, fmanager -> dbase);
	
	return ok;
}

void 
ClosefManager(fmanagerADT fmanager)
{
	if ( Precondicion(fmanager))
	{
		Error("ClosefManager@fmanagerADT.c - Invalid arguments\n");
		return;
	}
	if (Precondicion(fmanager -> dbase) )
	{
		 Error("ClosefManager@fmanagerADT.c - No file loaded\n");
		 return;
	}
	
	fclose(fmanager -> dbase);
	free(fmanager);
	
	return;
}
